//
//  SVGAPlayerUtil.swift
//  CocoProject
//
//  Created by Vill on 2023/11/3.
//

import Foundation
import SVGAPlayer

class SVGAPlayerUtil: NSObject {
    static let shared = SVGAPlayerUtil()
    private let svgaPlayer = SVGAPlayer()
    private let svgaParser = SVGAParser()
    
    var playView: UIView!
    
    var playerFrame = CGRect(x: 0, y: KStatusAndNavBarHeight, width: SCREENWIDTH, height: SCREENHEIGHT - KStatusAndNavBarHeight - KTabBarAndSafeHeight)
    
    var fileUrl: String! {
        didSet {
            playSVGA()
        }
    }

    convenience init(viewToPlay: UIView) {
        self.init()
        playView = viewToPlay
    }
    
    override init() {
        super.init()
        svgaPlayer.frame = playerFrame
        svgaPlayer.delegate = self;
        svgaPlayer.loops = 1
        svgaPlayer.clearsAfterStop = true
        svgaParser.enabledMemoryCache = false
    }
    
    func addToView(view: UIView) {
        view.addSubview(svgaPlayer)
    }
    
    // 播放svga
    private func playSVGA() {
        let cachePath = "\(fileUrl!.md5Hash()).svga"
        let fm = FileManager.default
        if fm.fileExists(atPath: cachePath), let svgaData = try? Data(contentsOf: URL(fileURLWithPath: cachePath)) {
            svgaParser.parse(with: svgaData, cacheKey: cachePath) { [weak self] (videoItem) in
                self!.playView.addSubview(self!.svgaPlayer)
                self!.svgaPlayer.videoItem = videoItem
                self!.svgaPlayer.startAnimation()
            } failureBlock: { (error) in
                print(error)
            }
        } else {
            if fileUrl.count == 0 {
                return
            }
            svgaParser.parse(with: KUrlImaged(fileUrl)!) { [weak self] videoItem in
                self!.playView.addSubview(self!.svgaPlayer)
                self!.svgaPlayer.videoItem = videoItem
                self!.svgaPlayer.startAnimation()
            } failureBlock: { (error) in
                print(error as Any)
            }
        }
    }
}

//MARK: -- SVGAPlayerDelegate
extension SVGAPlayerUtil:SVGAPlayerDelegate {
    func svgaPlayerDidFinishedAnimation(_ player: SVGAPlayer!) {
        svgaPlayer.stopAnimation()
        svgaPlayer.clear()
        svgaPlayer.removeFromSuperview()
    }
    
    func svgaPlayerDidAnimated(toPercentage percentage: CGFloat) {
//        print(percentage)
    }
}
